package org.demo.service.impl;

import java.util.List;

import org.demo.bean.Person;
import org.demo.service.PersonService;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务层:PersonBeanImpl
 * @author  
 * @date    2010-7-20
 * @file    org.demo.service.impl.PersonServiceImpl.java
 */
@Transactional
public class PersonServiceImpl implements PersonService {
	
	@Autowired //@Resource //[在 jdk1.6下]
	private SessionFactory sessionFactory;		
	/**true
	 * 保存
	 * @param person
	 */
	public void save(Person person){
		sessionFactory.getCurrentSession().persist(person);
	}
	/**
	 * 修改
	 * @param person
	 */
	public void update(Person person){
		sessionFactory.getCurrentSession().merge(person);
	}
	/**
	 * 删除
	 * @param personId
	 */
	public void delete(int personId){
		Object bean = sessionFactory
		             .getCurrentSession().load(Person.class,personId);
		sessionFactory.getCurrentSession().delete(bean);
	}
	/**
	 * 删除所有
	 */
	public void deleteAll(){
		List<Person> list = getAll();
		for (int i=0; i<list.size(); i++){
			sessionFactory.getCurrentSession().delete(list.get(i));
		}
	}
	/**
	 * 获取
	 * @param personId
	 * @return
	 */
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public Person get(int personId){
		return (Person)sessionFactory.getCurrentSession()
		                             .get(Person.class,personId);
	}
	/**
	 * 分页查询 [startRow < rowNum <= startRow + maxResult]
	 * @param startRow
	 * @param maxResult
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public List<Person> get(int startRow,int maxResult){
		Query query = sessionFactory.getCurrentSession()
                                    .createQuery("from Person");
		query.setFirstResult(startRow);
		query.setMaxResults(maxResult);
		return query.list();
	}
	/**
	 * 获取全部
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public List<Person> getAll(){
		return sessionFactory.getCurrentSession()
                             .createQuery("from Person").list();
	}
}